package org.example;

import bean.DB;
import bean.ResponseUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/deleteProductServlet")
public class deleteProductServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取商品 ID
        String id = request.getParameter("id");

        if (id == null || id.trim().isEmpty()) {
            ResponseUtils.sendResponse(response, "无效的商品 ID", "productPage.jsp");
            return;
        }

        // SQL 删除语句
        String deleteSql = "DELETE FROM products WHERE id = ?";
        DB db = new DB();

        try (Connection conn = db.createConn();
             PreparedStatement pstmt = conn.prepareStatement(deleteSql)) {
            pstmt.setInt(1, Integer.parseInt(id)); // 设置参数

            int rowsAffected = pstmt.executeUpdate(); // 执行删除
            if (rowsAffected > 0) {
                ResponseUtils.sendResponse(response, "商品删除成功", "productPage.jsp");
            } else {
                ResponseUtils.sendResponse(response, "商品不存在或删除失败", "productPage.jsp");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "商品已被下单", "productPage.jsp");
        }
    }
}
